@extends('layouts.default')

@section('title', '课题研究')

@push('scripts')
<script src="{{ asset('lib/xm-select-v1.2.4/xm-select.js')}}"></script>
<script>
    layui.use(['layer','form','table','laytpl','laydate','element','laypage','upload'], function(){
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var laytpl = layui.laytpl;
        var laydate = layui.laydate;
        var element = layui.element;
        var laypage = layui.laypage;
        var upload = layui.upload;
        var cxmDemo;
        var pxmDemo;
        var PageId = "{{request()->get('id',0)}}";
        var sbbFiles = [];
        var lxzmFiles = [];

        renderSelect();

        laydate.render({
            elem: '#begin-date'
            ,type: 'date'
        });
        laydate.render({
            elem: '#end-date'
            ,type: 'date'
        });
        laydate.render({
            elem: '#lxbegin-date'
            ,type: 'date'
        });
        laydate.render({
            elem: '#lxend-date'
            ,type: 'date'
        });

        //下拉框初始化
        async function renderSelect(){
            await renderDictionarySelect();
            await renderTermSelect();
            await renderCompere();
            await renderParticipants();
            pageInit();
        }

        //字典下拉框数据渲染
        function renderDictionarySelect() {
            return new Promise((resolve) => {
                getDictionaryItem({'diccode': ['LEVEL']}, function (res){
                    if(res.code === 1) {
                        let data = res.data;

                        for(var k in data) {
                            let key = k.toLowerCase();
                            let d = data[k];

                            $('[data-role='+key+'List]').empty().append('<option value="">请选择</option>');
                            for (var i in d) {
                                $('[data-role='+key+'List]').append('<option value="' + d[i].optionId + '">' + d[i].selectValue + '</option>');
                            }
                        }

                        form.render();

                        resolve();
                    }
                });
            });
        }

        //学期下拉框数据渲染
        function renderTermSelect() {
            return new Promise((resolve) => {
                getTermData({},function(res){
                    if(res.code == 1){
                        $('[data-role=termList]').empty().append('<option value="">请选择</option>');
                        for(var i in res.data){
                            $('[data-role=termList]').append('<option value="'+res.data[i].id+'">'+res.data[i].title+'</option>');
                        }

                        form.render('select');

                        resolve();
                    }
                });
            });
        }

        //主持人下拉框数据渲染
        function renderCompere() {
            return new Promise((resolve) => {
                getParticipantsData({},function(res){
                    if(res.code == 1){
                        cxmDemo = xmSelect.render({
                            el: '#cter',
                            autoRow: true,
                            filterable: true,
                            tree: {
                                show: true,
                                showFolderIcon: true,
                                showLine: true,
                                indent: 20,
                                expandedKeys:false
                            },
                            direction: 'down',
                            filterable: true,
                            height: 'auto',
                            name: 'compere',
                            layVerify: 'required',
                            layVerType: 'msg',
                            layReqText: '主持人不能为空',
                            theme: {
                                color: '#2d8cf0',
                            },
                            searchTips:'关键字搜索',
                            data: function(){
                                return res.data
                            }
                        });

                        return resolve();
                    }
                });
            });
        }

        //参与教师下拉框数据渲染
        function renderParticipants() {
            return new Promise((resolve) => {
                getParticipantsData({},function(res){
                    if(res.code == 1){
                        pxmDemo = xmSelect.render({
                            el: '#pter',
                            autoRow: true,
                            filterable: true,
                            tree: {
                                show: true,
                                showFolderIcon: true,
                                showLine: true,
                                indent: 20,
                                expandedKeys:false
                            },
                            direction: 'down',
                            filterable: true,
                            height: 'auto',
                            name: 'participant',
                            layVerify: 'required',
                            layVerType: 'msg',
                            layReqText: '参与教师不能为空',
                            theme: {
                                color: '#2d8cf0',
                            },
                            searchTips:'关键字搜索',
                            data: function(){
                                return res.data
                            }
                        });

                        return resolve();
                    }
                });
            });
        }

        window.fileDelete = function (fk, ft) {
            if(ft == 1) {
                delete sbbFiles[fk];
                let files = sbbFiles;

                $('#sbb-file').val(JSON.stringify(sbbFiles));
                $('#sbb-uploader').parent().find('.file-show').html('');
                for(i in files) {
                    if(files[i]) {
                        let fsHtml = '<div class="file-item"><span class="file-name">'+files[i].file_name+'</span><span class="layui-icon layui-icon-close-fill" onClick="fileDelete('+i+', 1)"></span></div>';
                        $('#sbb-uploader').parent().find('.file-show').append(fsHtml);
                    }
                }
            } else if(ft == 2) {
                delete lxzmFiles[fk];
                let files = lxzmFiles;

                $('#lxzm-file').val(JSON.stringify(lxzmFiles));
                $('#lxzm-uploader').parent().find('.file-show').html('');
                for(i in files) {
                    if(files[i]) {
                        let fsHtml = '<div class="file-item"><span class="file-name">'+files[i].file_name+'</span><span class="layui-icon layui-icon-close-fill" onClick="fileDelete('+i+', 2)"></span></div>';
                        $('#lxzm-uploader').parent().find('.file-show').append(fsHtml);
                    }
                }
            }
        }

        //文件上传
        upload.render({
            elem: '#sbb-uploader'
            ,url: "{{route('uploads.upload')}}" //此处配置你自己的上传接口即可
            ,accept: 'file' //普通文件
            ,multiple: true
            ,allDone: function(obj){ //当文件全部被提交后，才触发
                if(obj.total == obj.successful) {
                    //layer.msg('上传成功');
                } else {
                    layer.msg(obj.failed + '个文件上传失败！');
                }
            }
            ,done: function(res){
                if(res.code != 1) {
                    layer.msg(res.msg);
                    return false;
                }else{
                    layer.msg('上传成功');
                }
                sbbFiles.push(res.data);
                $('#sbb-file').val(JSON.stringify(sbbFiles));

                $('#sbb-uploader').parent().find('.file-show').html('');
                for(i in sbbFiles) {
                    if(sbbFiles[i]) {
                        let fsHtml = '<div class="file-item"><span class="file-name">'+sbbFiles[i].file_name+'</span><span class="layui-icon layui-icon-close-fill" onClick="fileDelete('+i+', 1)"></span></div>';
                        $('#sbb-uploader').parent().find('.file-show').append(fsHtml);
                    }
                }
            }
            ,error: function(index, upload){ //错误回调
                console.log(index);
            }
        });
        upload.render({
            elem: '#lxzm-uploader'
            ,url: "{{route('uploads.upload')}}" //此处配置你自己的上传接口即可
            ,accept: 'file' //普通文件
            ,multiple: true
            ,choose: function(obj){
                //上传loading
                showloading(true);
            }
            ,allDone: function(obj){ //当文件全部被提交后，才触发
                showloading(false);
                if(obj.total == obj.successful) {
                    //layer.msg('上传成功');
                } else {
                    layer.msg(obj.failed + '个文件上传失败！');
                }
            }
            ,done: function(res){
                if(res.code != 1) {
                    layer.msg(res.msg);
                    return false;
                }else{
                    layer.msg('上传成功');
                }
                lxzmFiles.push(res.data);
                $('#lxzm-file').val(JSON.stringify(lxzmFiles));

                $('#lxzm-uploader').parent().find('.file-show').html('');
                for(i in lxzmFiles) {
                    if(lxzmFiles[i]) {
                        let fsHtml = '<div class="file-item"><span class="file-name">'+lxzmFiles[i].file_name+'</span><span class="layui-icon layui-icon-close-fill" onClick="fileDelete('+i+', 2)"></span></div>';
                        $('#lxzm-uploader').parent().find('.file-show').append(fsHtml);
                    }
                }
            }
            ,error: function(index, upload){ //错误回调
                console.log(index);
            }
        });

        //数据渲染
        function pageInit(){
            getActivityOne({id:PageId}, function(res) {
                if(res.code === 1) {
                    let Activity = res.data;

                    if(Activity.level_array[0].optionId <= 108) {
                        $(".lx-item").removeClass('layui-hide');
                    }

                    form.val('editForm', {
                        'id': PageId,
                        'data_version_id': Activity.data_version_id,
                        'name': Activity.name,
                        'begin_date': Activity.begin_date,
                        'end_date': Activity.end_date,
                        'level': Activity.level_array[0].optionId,
                        'activity_category': Activity.activity_category,
                        'stage': Activity.stage
                    });

                    //主持人
                    cxmDemo.setValue(Activity.participants_users.pere);
                    //参与教师
                    pxmDemo.setValue(Activity.participants_users.pant);
                    //文件
                    if(Activity.proof_material_array.length){
                        layui.each(Activity.proof_material_array, function(i, d) {
                            if(d.field == 'sbb') {
                                sbbFiles.push(d.file_origin);
                                $('#sbb-file').val(JSON.stringify(sbbFiles));

                                $('#sbb-uploader').parent().find('.file-show').html('');
                                for(i in sbbFiles) {
                                    if(sbbFiles[i]) {
                                        let fsHtml = '<div class="file-item"><span class="file-name">'+sbbFiles[i].file_name+'</span><span class="layui-icon layui-icon-close-fill" onClick="fileDelete('+i+', 1)"></span></div>';
                                        $('#sbb-uploader').parent().find('.file-show').append(fsHtml);
                                    }
                                }
                            } else if(d.field == 'lxzm') {
                                lxzmFiles.push(d.file_origin);
                                $('#lxzm-file').val(JSON.stringify(lxzmFiles));

                                $('#lxzm-uploader').parent().find('.file-show').html('');
                                for(i in lxzmFiles) {
                                    if(lxzmFiles[i]) {
                                        let fsHtml = '<div class="file-item"><span class="file-name">'+lxzmFiles[i].file_name+'</span><span class="layui-icon layui-icon-close-fill" onClick="fileDelete('+i+', 1)"></span></div>';
                                        $('#lxzm-uploader').parent().find('.file-show').append(fsHtml);
                                    }
                                }
                            }
                        });
                    }

                    //立项证明时间
                    if(Activity.stages.length){
                        layui.each(Activity.stages, function(i, d) {
                            if(d.stage == 2) {
                                form.val('editForm', {
                                    'lx_begin_date': d.begin_date,
                                    'lx_end_date': d.end_date
                                });
                            }
                        });
                    }

                    form.render();
                } else {
                    layer.msg('无数据记录', {time: 2000, icon: 5});
                }
            });
        }

        form.on('select(levelList)', function(data){
            // console.log(data.elem); //得到select原始DOM对象
            // console.log(data.value); //得到被选中的值
            // console.log(data.othis); //得到美化后的DOM对象

            if(data.value <= 108) {
                $(".lx-item").removeClass('layui-hide');

                form.val('editForm', {
                    'stage': 2
                });
                form.render();
            } else {
                $(".lx-item").addClass('layui-hide');

                form.val('editForm', {
                    'stage': 1
                });
                form.render();
            }
        });

        //提交
        form.on('submit(sub)', function(data){
            let d = data.field;
            d.comperes = cxmDemo.getValue('nameStr');
            d.compere_ids = cxmDemo.getValue('value');
            d.participants = pxmDemo.getValue('nameStr');
            d.participant_ids = pxmDemo.getValue('value');
            d.do_task = 1;

            if(!d.activity_category) {
                layer.msg('请选择类别！', {icon: 5,shift : 6});
                return false;
            }

            editActivity(d, function(res){
                if(res.code == '1'){
                    layer.msg(res.msg,{icon: 6,time: 1000},function(){
                        window.history.back();
                    });
                }else{
                    layer.msg(res.msg, {icon: 5,shift : 6});
                }
            });

            return false;
        });
        //保存
        $('#save-btn').click(function(){
            var isValid = form.validate('.data-version-id');
            if(!isValid) return false;

            var data = form.val("editForm");
            data.comperes = cxmDemo.getValue('nameStr');
            data.compere_ids = cxmDemo.getValue('value');
            data.participants = pxmDemo.getValue('nameStr');
            data.participant_ids = pxmDemo.getValue('value');
            data.status = 2;
            if(!data.activity_category) {
                layer.msg('请选择类别！', {icon: 5,shift : 6});
                return false;
            }
            editActivity(data, function(res){
                if(res.code == '1'){
                    layer.msg(res.msg,{icon: 6,time: 1000},function(){
                        window.history.back();
                    });
                }else{
                    layer.msg(res.msg, {icon: 5,shift : 6});
                }
            });
            return false;
        });
    });
</script>
@endpush

@section('content')
<style>
    .opt-panel{padding: 10px;}
    .panel-title h3{margin-bottom: 20px;font-weight: 800;}

    .opt-form{padding: 20px 5px;}
    .opt-area{display: flex;flex-direction: row-reverse;padding: 10px 20px;margin-bottom: 20px;}
    .opt-area button, .back-btn{margin-left: 10px;}
</style>

<div class="layui-row">
    <div class="layui-panel opt-panel">
        <form class="layui-form opt-form" action="" id="edit-form" lay-filter="editForm">
            <div class="layui-row">
                <div class="panel-title">
                    <h3>课题研究 - 编辑</h3>
                </div>
                <div class="layuik-form-item layuik-columns-two">
                    <div class="layuik-inline">
                        <label class="layuik-form-label"><i class="redstar">*</i>学年学期：</label>
                        <div class="layuik-input-inline">
                            <select class="data-version-id" name="data_version_id" lay-filter="termList" data-role="termList" lay-verify="required" lay-reqText="不能为空"></select>
                        </div>
                    </div>
                    <div class="layuik-inline">
                        <label class="layuik-form-label"><i class="redstar">*</i>主题名称：</label>
                        <div class="layuik-input-inline">
                            <input type="text" name="name" required lay-verify="required" placeholder="请输入" lay-reqText="不能为空" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layuik-form-item layuik-columns-two">
                    <div class="layuik-inline">
                        <label class="layuik-form-label"><i class="redstar">*</i>开始日期：</label>
                        <div class="layuik-input-inline">
                            <input type="text" name="begin_date" id="begin-date" required lay-verify="required" placeholder="请选择" lay-reqText="不能为空" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layuik-inline">
                        <label class="layuik-form-label"><i class="redstar">*</i>结束日期：</label>
                        <div class="layuik-input-inline">
                            <input type="text" name="end_date" id="end-date" required lay-verify="required" placeholder="请选择" lay-reqText="不能为空" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layuik-form-item layuik-columns-two">
                    <div class="layuik-inline">
                        <label class="layuik-form-label"><i class="redstar">*</i>级别：</label>
                        <div class="layuik-input-inline">
                            <select name="level" lay-filter="levelList" data-role="levelList" lay-verify="required" lay-reqText="不能为空"></select>
                        </div>
                    </div>
                    <div class="layuik-inline">
                        <label class="layuik-form-label"><i class="redstar">*</i>类别：</label>
                        <div class="layuik-input-inline">
                            <input type="radio" name="activity_category" value="EW_SUBJECT_RESEARCH_TABLE" title="教育" class="layui-radio">
                            <input type="radio" name="activity_category" value="TEARRESEARCH_SUBJECT_STUDY_TABLE" title="教学" class="layui-radio">
                        </div>
                    </div>
                </div>
                <div class="layuik-form-item">
                    <div class="layuik-inline">
                        <label class="layuik-form-label"><i class="redstar">*</i>主持人：</label>
                        <div class="layuik-input-inline">
                            <div type="text" id="cter" class="xm-select-demo"></div>
                        </div>
                    </div>
                </div>
                <div class="layuik-form-item">
                    <div class="layuik-inline">
                        <label class="layuik-form-label"><i class="redstar">*</i>参与教师：</label>
                        <div class="layuik-input-inline">
                            <div type="text" id="pter" class="xm-select-demo"></div>
                        </div>
                    </div>
                </div>
                <div class="layuik-form-item layuik-columns-two">
                    <div class="layuik-inline">
                        <label class="layuik-form-label"><i class="redstar">*</i>课题阶段：</label>
                        <div class="layuik-input-inline">
                            <select name="stage" lay-filter="stageList" data-role="stageList" lay-verify="required" lay-reqText="不能为空" disabled>
                                <option value="">请选择</option>
                                <option value="1" selected>申报阶段</option>
                                <option value="2">立项阶段</option>
                                <option value="3">中期阶段</option>
                                <option value="4">结项阶段</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="layuik-form-item layuik-columns-two">
                    <div class="layuik-inline">
                        <label class="layuik-form-label">申报表：</label>
                        <div class="layuik-input-inline layuik-upload">
                            <button type="button" class="layui-btn layui-btn-normal" id="sbb-uploader"><i class="layui-icon"></i>上传文件</button>
                            <div class="file-show"></div>
                            <input style="display:none" type="text" id="sbb-file" name="files[sbb]" value="">
                        </div>
                    </div>
                </div>
                <div class="layuik-form-item layuik-columns-two lx-item layui-hide">
                    <div class="layuik-inline">
                        <label class="layuik-form-label">立项开始时间：</label>
                        <div class="layuik-input-inline">
                            <input type="text" name="lx_begin_date" id="lxbegin-date" placeholder="请选择" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layuik-inline">
                        <label class="layuik-form-label">立项结束时间：</label>
                        <div class="layuik-input-inline">
                            <input type="text" name="lx_end_date" id="lxend-date" placeholder="请选择" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layuik-form-item layuik-columns-two lx-item layui-hide">
                    <div class="layuik-inline">
                        <label class="layuik-form-label">立项证明：</label>
                        <div class="layuik-input-inline layuik-upload">
                            <button type="button" class="layui-btn layui-btn-normal" id="lxzm-uploader"><i class="layui-icon"></i>上传文件</button>
                            <div class="file-show"></div>
                            <input style="display:none" type="text" id="lxzm-file" name="files[lxzm]" value="">
                        </div>
                    </div>
                </div>
            </div>

            <div class="layui-row">
                <div class="opt-area">
                    <a href="javascript:history.go(-1);" class="layui-btn layui-btn-primary back-btn">返回</a>
                    <button class="layui-btn layui-btn-primary"  id="save-btn" style="color:#2d8cf0;" >保存</button>
                    <button class="layui-btn layui-btn-normal" lay-submit lay-filter="sub">提交</button>
                    <input type="hidden" name="id" value="">
                </div>
            </div>
        </form>
    </div>
</div>

@endsection
